//
//  ExerStartVc.m
//  CareRingApp
//
//  Created by Linktop on 2023/7/17.
//  锻炼下发开始界面

#import "ExerStartVc.h"
#import <QMUIKit/QMUIKit.h>
#import <Masonry/Masonry.h>
#import "UIViewController+Custom.h"
#import "ConfigModel.h"
#import "DeviceCenter.h"
#import "DBExercise.h"

#import "SelectItem.h"
#import "SRDeviceInfo+description.h"
#import "ExerRecordVc.h"
#import "TimeUtils.h"
#import "ExerTypeChooseVc.h"

const CGFloat EXEC_ITEM_HEIGHT = 55.f;

@interface ExerStartVc ()<SRBleScanProtocal, SRBleDataProtocal>

@property(strong, nonatomic)QMUIButton *startBtn;
@property(strong, nonatomic)DBExercise *exerObj;

@property(strong, nonatomic)NSArray<NSNumber *> *durationsArray; // 锻炼时长数组
@property(strong, nonatomic)SelectItem *workoutTitle, *detailTitle;
@property(weak, nonatomic) SelectItem *durationItem, *intensityItem;

@property(strong, nonatomic)SelectItem *moreTypeItem;

@property(strong, nonatomic)NSMutableArray<SelectItem *> *workOutItemArray, *detailtItemArray;

@property(assign, nonatomic)NSUInteger todayCount;
@property(strong, nonatomic)NSMutableArray<NSNumber *> *workoutTypeArray; //类型

@end

@implementation ExerStartVc


- (void)viewDidLoad {
    [super viewDidLoad];
    [self arrowback:nil];
    
    [self initUI];
    
    
    [DeviceCenter instance].appDataDelegate = self;
    [DeviceCenter instance].sRappScanDelegate = self;
    
    [self queryTodayCount]; // 查询今天已经有的锻炼数量
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self setStartBtnState:[DeviceCenter instance].isBleConnected];

}

-(void)initUI {
    self.navigationItem.title = _L(L_NAV_TITLE_EXERCISE); //锻炼
    
    UIButton *navHistoryBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [navHistoryBtn setImage:[UIImage imageNamed:@"mindful_his_btn"] forState:UIControlStateNormal];
    [navHistoryBtn addTarget:self action:@selector(gotoShowHistory:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithCustomView:navHistoryBtn];
    self.navigationItem.rightBarButtonItem = item;
    
    // 布局
    UIView *topCnt = [UIView new];
    UIView *midCnt = [UIView new];
    UIView *bottomCnt = [UIView new];
    
    [self.view addSubview:self.workoutTitle];
    [self.view addSubview: self.detailTitle];

    
    
    [self.view addSubview:topCnt];
    [self.view addSubview:midCnt];
    [self.view addSubview:bottomCnt];
    
    [self.workoutTitle mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.view.mas_leading).offset(20);
        make.trailing.equalTo(self.view.mas_trailing).inset(20);
        make.height.equalTo(@(40));
        make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop).offset(10);

    }];
    
    
    [topCnt mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.workoutTitle.mas_leading);
        make.trailing.equalTo(self.workoutTitle.mas_trailing);
        make.top.equalTo(self.workoutTitle.mas_bottom);
//        make.height.equalTo(self.view.mas_height).multipliedBy(1/3.0);

    }];
    
    [self.detailTitle mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.workoutTitle.mas_leading);
        make.trailing.equalTo(self.workoutTitle.mas_trailing);
        make.top.equalTo(topCnt.mas_bottom).offset(10);
        make.height.equalTo(self.workoutTitle);
    }];
    
    [midCnt mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(topCnt.mas_leading);
        make.trailing.equalTo(topCnt.mas_trailing);
        make.top.equalTo(self.detailTitle.mas_bottom);
//        make.height.equalTo(self.view.mas_height).multipliedBy(1/3.0);
    }];
    
    [bottomCnt mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(topCnt.mas_leading);
        make.trailing.equalTo(topCnt.mas_trailing);
        make.top.equalTo(midCnt.mas_bottom).offset(10);
    }];
    
    [self.view addSubview:self.startBtn];
    [self.startBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.height.equalTo(@44);
        make.top.equalTo(bottomCnt.mas_bottom).offset(30);
        make.width.equalTo(self.view.mas_width).multipliedBy(2/3.0);
    }];
    
    [self layoutTop:topCnt];
    [self layoutMid:midCnt];
    [self layoutBottom:bottomCnt];

}

-(void)layoutTop:(UIView *)cnt {
//    cnt.layer.borderWidth = 1;
//    cnt.layer.borderColor = SEPLINE_COLOR(1).CGColor;
    cnt.layer.cornerRadius = ITEM_CORNOR_RADIUS;
    cnt.layer.masksToBounds = YES;
    cnt.backgroundColor = ITEM_BG_COLOR;
    
    for (int i = 0; i < self.workOutItemArray.count; i++) {
        [cnt addSubview:self.workOutItemArray[i]];
    }
    for (int i = 0; i < self.workOutItemArray.count; i++) {
        SelectItem *v = self.workOutItemArray[i];
        [v mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.leading.trailing.equalTo(v.superview);
            if (i == 0) {
                make.top.equalTo(v.superview.mas_top);
            }
//            if (i == self.workOutItemArray.count-1) {
//                make.bottom.equalTo(v.superview.mas_bottom);
//            }
            if (i > 0 && self.workOutItemArray.count > 1) {
                make.top.equalTo(self.workOutItemArray[i-1].mas_bottom);
            }
            make.height.equalTo(@(EXEC_ITEM_HEIGHT));

        }];
    }
    [cnt addSubview:self.moreTypeItem];
    [self.moreTypeItem mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.workOutItemArray.lastObject.mas_bottom);
        make.leading.trailing.equalTo(self.workOutItemArray.lastObject);
        make.height.equalTo(self.workOutItemArray.lastObject.mas_height);
        
        make.bottom.equalTo(self.moreTypeItem.superview.mas_bottom);

    }];
    
}

-(void)layoutMid:(UIView *)cnt {
//    cnt.layer.borderWidth = 1;
//    cnt.layer.borderColor = SEPLINE_COLOR(1).CGColor;
    cnt.layer.cornerRadius = ITEM_CORNOR_RADIUS;
    cnt.layer.masksToBounds = YES;
    cnt.backgroundColor = ITEM_BG_COLOR;

    for (int i = 0; i < self.detailtItemArray.count; i++) {
        [cnt addSubview:self.detailtItemArray[i]];
    }
    
    for (int i = 0; i < self.detailtItemArray.count; i++) {
        SelectItem *v = self.detailtItemArray[i];
        [v mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.leading.trailing.equalTo(v.superview);
            if (i == 0) {
                make.top.equalTo(v.superview.mas_top);
            }
            if (i == self.detailtItemArray.count-1) {
                make.bottom.equalTo(v.superview.mas_bottom);
            }
            if (i > 0 && self.detailtItemArray.count > 1) {
                make.top.equalTo(self.detailtItemArray[i-1].mas_bottom);
            }
            make.height.equalTo(@(EXEC_ITEM_HEIGHT));

        }];
    }
}

-(void)layoutBottom:(UIView *)cnt {
    
    SelectItem *easy = [[SelectItem alloc]initWithStyle:DESC_STYLE];
    SelectItem *moderate = [[SelectItem alloc]initWithStyle:DESC_STYLE];
    SelectItem *hard = [[SelectItem alloc]initWithStyle:DESC_STYLE];
    
    easy.leftLbl.font = [UIFont systemFontOfSize:15];
    moderate.leftLbl.font = [UIFont systemFontOfSize:15];
    hard.leftLbl.font = [UIFont systemFontOfSize:15];

    
    [easy setLeftText:[NSString stringWithFormat:@"%@%@%@",_L(L_EASY), _L(L_COLON), _L(L_EASY_EXEC_DETAL)]];
    [moderate setLeftText:[NSString stringWithFormat:@"%@%@%@",_L(L_MODERATE), _L(L_COLON), _L(L_MODERATE_EXEC_DETAL)]];
    [hard setLeftText:[NSString stringWithFormat:@"%@%@%@",_L(L_HARD), _L(L_COLON), _L(L_HARD_EXEC_DETAL)]];

    NSArray<SelectItem *> *arr = @[easy, moderate, hard];
    
    for (int i = 0; i < arr.count; i++) {
        [cnt addSubview:arr[i]];
    }
    
    for (int i = 0; i < arr.count; i++) {
        SelectItem *v = arr[i];
        [v mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.leading.trailing.equalTo(v.superview);
            if (i == 0) {
                make.top.equalTo(v.superview.mas_top);
            }
            if (i == arr.count-1) {
                make.bottom.equalTo(v.superview.mas_bottom);
            }
            if (i > 0 && arr.count > 1) {
                make.top.equalTo(arr[i-1].mas_bottom);
            }
            make.height.equalTo(@(30));

        }];
    }
    
}


-(void)queryTodayCount {
    WEAK_SELF
    [DBExercise queryBy:[DeviceCenter instance].bindDevice.macAddress BeginDate:[TimeUtils zeroOfDate:[NSDate date]] EndDate:[TimeUtils zeroOfNextDayDate:[NSDate date]] OrderBeTimeDesc:YES Cpmplete:^(NSMutableArray<DBExercise *> * _Nonnull results) {
        STRONG_SELF
        strongSelf.todayCount = results.count;
        
    }];
    
}

#pragma mark --开始按钮点击
-(void)setStartBtnState:(BOOL)bleConnected {
    if (bleConnected) {
        self.startBtn.enabled = YES;
        self.startBtn.backgroundColor = MAIN_BLUE;
    } else {
        self.startBtn.enabled = NO;
        self.startBtn.backgroundColor = UIColor.lightGrayColor;
    }
}

/// 历史列表
/// - Parameter btn:
-(void)gotoShowHistory:(UIButton *)btn {
    
    ExerRecordVc *vc = [[ExerRecordVc alloc]init];
    
    [self.navigationController pushViewController:vc animated:YES];
    
}

-(void)startExer:(QMUIButton *)btn {
    
    if (self.todayCount >= MAX_ERERCISE_ONE_DAY) {
        // 到达限制
        [self showAlertWarningWithTitle:_L(L_TIPS) Msg:[NSString stringWithFormat:_L(L_TIP_MAX_ERERCISE), MAX_ERERCISE_ONE_DAY] btnOk:_L(L_OK) OkBLk:^{
            
        } CancelBtn:nil CancelBlk:nil Compelete:nil];
        
        return;
    }
    

    
    if ([DeviceCenter instance].isCharging) { // 充电中
        [[LTPHud Instance] showText:_L(L_TXT_REASON_IS_CHARGING)];

        return;
    }
    
    self.exerObj.startDate = [NSDate date];
    // send cmd
    WORKOUT_TYPE wkType = WORKOUT_TYPE_OTHER;
    if (self.exerObj.exerType == EXER_RUN || self.exerObj.exerType == EXER_WALK || self.exerObj.exerType == EXER_RUN_OUTDOOR)
    {
        wkType = WORKOUT_TYPE_RUNNING;
    }
    [[DeviceCenter instance].sdk functionStartSportMode:self.exerObj.duration.unsignedShortValue
                                          ValueInterval:EXER_TAKE_DATA_SECONDS WorkType:wkType];
    [[LTPHud Instance] showHudLasting:3];
    
}


-(void)chooseDuration {
    
    WEAK_SELF
    UIAlertController * alertVc = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    for (NSNumber *num in self.durationsArray) {
        
        UIAlertAction *actionDura = [UIAlertAction actionWithTitle:[DBExercise durationString:num.intValue] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            STRONG_SELF
            strongSelf.exerObj.duration = num;
            [strongSelf.durationItem setRightText:[strongSelf.exerObj durationString:NO]];
            
        }];

        [alertVc addAction:actionDura];
    }
    
    UIAlertAction * actionCancel = [UIAlertAction actionWithTitle:_L(L_CANCEL) style:UIAlertActionStyleCancel handler:nil];
    [alertVc addAction:actionCancel];

    [self presentViewController:alertVc animated:YES completion:nil];
    
}

-(void)chooseIntensity {

    NSArray<NSNumber *> *arrray = @[@(LEVEL_EASY), @(LEVEL_MODERATE), @(LEVEL_HARD),];
    
    WEAK_SELF
    UIAlertController * alertVc = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    for (NSNumber *num in arrray) {
        
        UIAlertAction *actionDura = [UIAlertAction actionWithTitle:[DBExercise stringForLevel:num.intValue] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            STRONG_SELF
            strongSelf.exerObj.exerLevel = num.intValue;
            [strongSelf.intensityItem setRightText:[strongSelf.exerObj stringForLevel]];
            
        }];

        [alertVc addAction:actionDura];
    }
    
    UIAlertAction * actionCancel = [UIAlertAction actionWithTitle:_L(L_CANCEL) style:UIAlertActionStyleCancel handler:nil];
    [alertVc addAction:actionCancel];

    [self presentViewController:alertVc animated:YES completion:nil];
    
}


#pragma mark -- ble delegates

- (void)srBleCmdExcute:(EXCUTED_CMD)cmd Succ:(BOOL)isSucc Reason:(CMD_EXECTE_ERROR_REASON)reason {
    
    if (cmd == EXCUTED_CMD_SPORT_MODE) { // 运动模式
        [[LTPHud Instance] hideHud];
        if (!isSucc) {
            NSString *string = [SRDeviceInfo descryOfErrorReason:reason];
            if (string.length) {
                [self showAlertWarningWithTitle:_L(L_TIPS) Msg:string btnOk:_L(L_OK) OkBLk:^{
                    
                } CancelBtn:nil CancelBlk:nil Compelete:nil];
            }
           
        } else {
            // 保存
            WEAK_SELF
            [self.exerObj insert:^(BOOL succ) {
                STRONG_SELF
                if (succ) {
                    if (strongSelf.callback) {
                        strongSelf.callback();
                    }
                    [strongSelf.navigationController popViewControllerAnimated:YES];

                }
            }];
        }
       
        
        return;
    }
   
}

- (void)srBleDeviceBatteryLevel:(NSInteger)batteryLevel IsCharging:(BOOL)isCharging {
    
}

- (void)srBleDeviceDidReadyForReadAndWrite:(nonnull SRBLeService *)service {
    [self setStartBtnState:YES];

}

- (void)srBleDeviceInfo:(nonnull SRDeviceInfo *)devInfo {
    
}

- (void)srBleDeviceRealtimeSteps:(nonnull NSNumber *)steps IsDeviceFix:(BOOL)isDeviceFixed{
    
}

- (void)srBleDeviceRealtimeTemperature:(nonnull NSNumber *)temperature {
    
}

- (void)srBleDidConnectPeripheral:(nonnull SRBLeService *)service {
}

- (void)srBleDidDisconnectPeripheral:(nonnull SRBLeService *)service {
    [self setStartBtnState:NO];
    [[LTPHud Instance] hideHud];
    
    [self showAlertWarningWithTitle:_L(L_TIPS) Msg:_L(L_TIPS_DEVICE_BLE_DISCED) btnOk:_L(L_OK) OkBLk:^{
        
    } CancelBtn:nil CancelBlk:nil Compelete:nil];
    
}


- (void)srBleHistoryDataTimeout {
    
}



- (void)srBleMeasureDuration:(NSInteger)seconds {
    
}

- (void)srBleOEMAuthResult:(BOOL)authSucceddful {
    
}



- (void)srBleSN:(nonnull NSString *)sn SnData:(nonnull NSData *)snData {
    
}

- (void)srBleSOShappen {
    
}

- (void)srBlesSOSData:(float)temperature HeartRate:(NSInteger)hr BloodOxygen:(NSInteger)bloodOxygen {
    
}

-(void)freshItems {
    
    for (int i = 0; i < self.workOutItemArray.count; i++) {
        SelectItem *item = self.workOutItemArray[i];
        NSNumber *type = self.workoutTypeArray[i];
        item.data = type; // 标记类型
        [item setLeftText:[DBExercise stringForExerType:type.intValue]];
        
    }
  
}
#pragma mark --lazy

- (QMUIButton *)startBtn
{
    if (!_startBtn) {
        _startBtn = [[QMUIButton alloc]init];
        _startBtn.backgroundColor = UIColor.lightGrayColor;
        
        _startBtn.cornerRadius = ITEM_CORNOR_RADIUS;
        [_startBtn setTitle:_L(L_BGSTART) forState:UIControlStateNormal];
        
        [_startBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
        [_startBtn addTarget:self action:@selector(startExer:) forControlEvents:UIControlEventTouchUpInside];
        _startBtn.enabled = NO; // 初始不可用
    }
    return _startBtn;
}

-(DBExercise *)exerObj
{
    if (!_exerObj) {
        _exerObj = [[DBExercise alloc]initWith:[DeviceCenter instance].bindDevice.macAddress];
        _exerObj.duration = @(30); // 默认 30分钟
        _exerObj.exerLevel = LEVEL_MODERATE; // 默认中等
        _exerObj.exerType = EXER_RUN; // 默认
    }
    return _exerObj;
}

-(NSArray<NSNumber *> *)durationsArray
{
    if (!_durationsArray) {
        _durationsArray = @[@(15), @(30), @(45), @(60), @(60 * 2), @(60 * 3)];
    }
    return _durationsArray;
}


-(SelectItem *)workoutTitle
{
    if (!_workoutTitle) {
        _workoutTitle = [[SelectItem alloc]initWithStyle:TITLE_STYLE];
        [_workoutTitle setLeftText:_L(L_TITLE_WORKOUT)];
    }
    return _workoutTitle;
}

-(SelectItem *)detailTitle
{
    if (!_detailTitle) {
        _detailTitle = [[SelectItem alloc]initWithStyle:TITLE_STYLE];
        [_detailTitle setLeftText:_L(L_TITLE_EXECR_DETAIL)];
    }
    return _detailTitle;
}

-(void)workoutCLick:(SelectItem *)item {
    
    item.selected = YES;//!item.selected;
    for (SelectItem *v in self.workOutItemArray) {
        if (v != item) {
            v.selected = NO;//!item.selected;
        }
    }
    
    self.exerObj.exerType = [item.data intValue];
    
}

-(NSMutableArray<SelectItem *> *)workOutItemArray
{
    if (!_workOutItemArray) {
        _workOutItemArray = [NSMutableArray new];
        
        SelectItem *runItem = [[SelectItem alloc]initWithStyle:NORMAL_STYLE];
        [runItem addBottomSepLine:SEPLINE_COLOR(0.3) Width:0.3];
        runItem.data = @(EXER_RUN); // 标记跑步
        [runItem setLeftText:_L(L_RUNNING)];
        WEAK_SELF
        runItem.clickBLK = ^(SelectItem * _Nonnull view) {
            STRONG_SELF
            [strongSelf workoutCLick:view];
        };
        
        SelectItem *walkITem = [[SelectItem alloc]initWithStyle:NORMAL_STYLE];
//        [walkITem addBottomSepLine:SEPLINE_COLOR(1) Width:1];
        walkITem.data = @(EXER_WALK); // 标记走路
        walkITem.clickBLK = ^(SelectItem * _Nonnull view) {
            STRONG_SELF
            [strongSelf workoutCLick:view];
        };
        [walkITem setLeftText:_L(L_WALKING)];

        [_workOutItemArray addObject:runItem];
        [_workOutItemArray addObject:walkITem];
        
        runItem.selected = self.exerObj.exerType == EXER_RUN;
        walkITem.selected = self.exerObj.exerType == EXER_WALK;
    }
    return _workOutItemArray;
}

-(NSMutableArray<SelectItem *> *)detailtItemArray
{
    if (!_detailtItemArray) {
        _detailtItemArray = [NSMutableArray new];
        WEAK_SELF
        SelectItem *durationItem = [[SelectItem alloc]initWithStyle:REMRK_STYLE];
        [durationItem addBottomSepLine:SEPLINE_COLOR(0.3) Width:0.3];
        [durationItem setLeftText:_L(L_EXERC_DURATION)];
        [durationItem setRightText:[self.exerObj durationString:NO]];
        durationItem.clickBLK = ^(SelectItem * _Nonnull view) {
            STRONG_SELF
            [strongSelf chooseDuration];
        };
        [_detailtItemArray addObject:durationItem];
        
        SelectItem *intensityItem = [[SelectItem alloc]initWithStyle:REMRK_STYLE];
        [intensityItem setLeftText:_L(L_EXERC_INTERNSITY)];
        [intensityItem setRightText:[self.exerObj stringForLevel]];
        
        [intensityItem setClickBLK:^(SelectItem * _Nonnull view) {
            STRONG_SELF
            [strongSelf chooseIntensity];
        }];
        [_detailtItemArray addObject:intensityItem];
        self.durationItem = durationItem;
        self.intensityItem = intensityItem;
    }
    return _detailtItemArray;
}

-(SelectItem *)moreTypeItem
{
    if (!_moreTypeItem) {
        
        WEAK_SELF
        _moreTypeItem = [[SelectItem alloc]initWithStyle:MORE_STYLE];
//        [_moreTypeItem addBottomSepLine:SEPLINE_COLOR(0.3) Width:0.3];
        [_moreTypeItem setLeftText:_L(L_MORE_EXERCISE)]; // 更多锻炼
        [_moreTypeItem setRightText:[self.exerObj durationString:NO]];
        _moreTypeItem.clickBLK = ^(SelectItem * _Nonnull view) {
            STRONG_SELF
            // 跳转选择更多
            ExerTypeChooseVc *vc = [[ExerTypeChooseVc alloc]init];
            vc.existTypeArray = strongSelf.workoutTypeArray;
            vc.callBack = ^(NSNumber * _Nonnull chooseType) {
                STRONG_SELF
                [strongSelf.workoutTypeArray removeLastObject];
                [strongSelf.workoutTypeArray insertObject:chooseType atIndex:0];
                
                [strongSelf freshItems];
                [strongSelf workoutCLick:strongSelf.workOutItemArray.firstObject];
            };
            
            [strongSelf.navigationController pushViewController:vc animated:YES];
        };
    }
    return _moreTypeItem;
    
}

-(NSMutableArray<NSNumber *> *)workoutTypeArray
{
    if (!_workoutTypeArray) {
        _workoutTypeArray = [NSMutableArray new];
        [_workoutTypeArray addObjectsFromArray:@[@(EXER_WALK), @(EXER_RUN) ]];
    }
    return _workoutTypeArray;
}

@end
